package com.anysoft.guide;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.utils.MentorLogger;
import com.facebook.cache.common.CacheKey;
import com.facebook.common.references.CloseableReference;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.GetStartupAdvertisementBean;
import com.anysoft.home.HomeActivity;
import com.anysoft.utils.StatusBarUtils;
import com.anysoft.web.BannerUrlActivity;
import com.anysoft.web.FundDetailActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by wwq on 2016/12/6.
 */

public class GuideCountDownNewStyleActivity extends BaseActivity {

    @BindView(R.id.sdv_count_down_bg)
    SimpleDraweeView sdvCountDownBg;
    @BindView(R.id.tv_count_down_time)
    TextView tvCountDownTime;
    @BindView(R.id.ll_count_down)
    LinearLayout llCountDown;

    private GetStartupAdvertisementBean advertisementBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guide_count_down_new_style_activity);
        ButterKnife.bind(this);
        StatusBarUtils.fullScreen(mActivity);
        advertisementBean = (GetStartupAdvertisementBean) getIntent().getSerializableExtra("bean");

        Uri imageUri = Uri.parse(advertisementBean.getData().getImage());

        Postprocessor myPostprocessor = new Postprocessor() {
            @Override
            public CloseableReference<Bitmap> process(Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) {
                return null;
            }

            @Override
            public String getName() {
                return null;
            }

            @Nullable
            @Override
            public CacheKey getPostprocessorCacheKey() {
                return null;
            }
        };

        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(imageUri)
                .setPostprocessor(myPostprocessor)
                .build();

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setOldController(sdvCountDownBg.getController())
                // 其他设置
                .build();

        sdvCountDownBg.setController(controller);
        sdvCountDownBg.setImageURI(imageUri);

        timeCount = new TimeCount(COUNT_DOWN_SECOND * 1000, 1000);
        timeCount.start();
    }

    private static final int COUNT_DOWN_SECOND = 5;
    private int count_down_time;
    private TimeCount timeCount;

    /**
     * 计时器
     */
    class TimeCount extends CountDownTimer {
        /**
         * @param millisInFuture    总时长
         * @param countDownInterval 计时间隔
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
            count_down_time = COUNT_DOWN_SECOND;
        }

        @Override
        public void onFinish() {// 计时完毕时触发
//            tvCountDownTime.setText("0");
            if (isGotoHome) {
                startActivity(new Intent().setClass(GuideCountDownNewStyleActivity.this, HomeActivity.class));
                finish();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            //System.out.println("millisUntilFinished---" + (millisUntilFinished / 1000));
            //因为在最后一秒的时候会多走一秒，目前没有找到原因，所以先这样设计
            if (count_down_time - 2 > 0) {
                tvCountDownTime.setText(count_down_time - 2 + "");
                count_down_time -= 1;
            } else {
                if (isGotoHome) {
                    startActivity(new Intent().setClass(GuideCountDownNewStyleActivity.this, HomeActivity.class));
                    finish();
                }
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.onPause();
    }

    private boolean isGotoHome = true;

    @OnClick({R.id.sdv_count_down_bg, R.id.ll_count_down})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sdv_count_down_bg:
                if (advertisementBean != null && advertisementBean.getData() != null) {
                    String pathUrl = advertisementBean.getData().getUrl();
                    if (!TextUtils.isEmpty(pathUrl)) {
                        if (pathUrl.contains("fundDetail.html")) {
                            String url = null;
                            try {
                                url = URLDecoder.decode(pathUrl, "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            MentorLogger.Log(TAG, "url=" + url);
                            String fundcode;
                            String fundType;
                            String mainTitle;
                            String subTitle;
                            Map<String, String> map = new HashMap<>();
                            String[] params = url.split("\\?")[1].split("&");
                            for (int i = 0; i < params.length; i++) {
                                //System.out.println("params--" + params[i]);
                                String key = params[i].split("=")[0];
                                String value = "";
                                try {
                                    value = params[i].split("=")[1];
                                } catch (Exception exception) {
                                    MentorLogger.Log(TAG, "value为null");
                                }
                                map.put(key, value);
                            }
                            fundcode = map.get("fundCode");
                            fundType = map.get("fundType");
                            mainTitle = map.get("fundName") + "  " + map.get("fundCode");
                            subTitle = map.get("fundstateDescription");

                            Intent mIntent = new Intent();
                            mIntent.setClass(mActivity, FundDetailActivity.class);
                            mIntent.putExtra("fundcode", fundcode);
                            mIntent.putExtra("fundType", fundType);
                            mIntent.putExtra("fundname", map.get("fundName"));
                            mIntent.putExtra("mainTitle", mainTitle);
                            mIntent.putExtra("subTitle", subTitle);
                            mIntent.putExtra("isFromGuide", true);
                            startActivity(mIntent);
                            isGotoHome = false;
                            finish();
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(mActivity, BannerUrlActivity.class);
                            intent.putExtra("bannerUrl", advertisementBean.getData().getUrl());
                            intent.putExtra("isFromGuide", true);
                            intent.putExtra("startBanner", true);
                            startActivity(intent);
                            isGotoHome = false;
                            finish();
                        }
                    }
                }
                break;
            case R.id.ll_count_down:
                startActivity(new Intent().setClass(GuideCountDownNewStyleActivity.this, HomeActivity.class));
                if (timeCount != null) {
                    timeCount.cancel();
                }
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.onDestroy();
    }
}
